package com.geostar.gmp.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class FileUtils {

	private static Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
	
	/** InputStream对象 **/
	private static InputStream in;
	
	/** Properties对象 **/
	private static Properties prop = new Properties();
	/**
	 * 目的: 获取Properties对象
	 * @param filePath 需要加载的Properties文件的路径
	 * @return Properties对象
	 * @throws IOException
	 */
	public static void initProp(String filePath) {
		in = FileUtils.class.getResourceAsStream(filePath);
		try {
			prop.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	/**
	 * 目的: 根据key获取对应的value值，Properties类本身提供了getProperty方法，
	 *      但是系统解析.propertes文件时是使用的"ISO8859-1"编码格式，所以在获得
	 *      value之后需要进行一次编码转换
	 * @param key 
	 * @return value值
	 *  
	 */
	public static String getProperty(String key){
		String value = prop.getProperty(key);
		try {
			value = new String(value.getBytes("ISO8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			LOGGER.info("编码格式转换错误");
		}
		return value;
	}
	
	/**
	 * 目的: 关闭IO流,重新new Properties;
	 */
	public static void closeProp() {
		if(in != null){
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				prop = new Properties();
			}
		}
	}
	
	public static void main(String[] args) {
		String MIB_FILE_PATH = "/mib.properties";
		initProp(MIB_FILE_PATH);
		String name = getProperty(".1.3.6.1.2.1.1.5.0");
		System.out.println("name:" +name);
		closeProp();
	}
}
